package com.maoxx.humanresourcemanage_service.service;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Quarter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.maoxx.humanresourcemanage_service.dto.Response;
import com.maoxx.humanresourcemanage_service.dto.ResponseDTO;
import com.maoxx.humanresourcemanage_service.entity.Attendance;
import com.maoxx.humanresourcemanage_service.entity.City;
import com.maoxx.humanresourcemanage_service.entity.Dept;
import com.maoxx.humanresourcemanage_service.entity.Staff;
import com.maoxx.humanresourcemanage_service.enums.AttendanceStatusEnum;
import com.maoxx.humanresourcemanage_service.mapper.AttendanceMapper;
import com.maoxx.humanresourcemanage_service.utils.DatetimeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class HomeService {

    @Resource
    private StaffService staffService;

    @Resource
    private AttendanceService attendanceService;

    @Resource
    private CityService cityService;

    @Resource
    private AttendanceMapper attendanceMapper;

    @Resource
    private DeptService deptService;


    // 统计当前年份入职员工数量
    public ResponseDTO getStaffData() {

        // 构建出当年xxxx-01-01到当年xxxx-12-31的条件
        QueryWrapper<Staff> qw
                = new QueryWrapper<Staff>().ge("create_time", DateUtil.thisYear() + "-01-01");

        // 进行查找
        List<Staff> staffList = staffService.list(qw);

        // 四个季度
        int q1 = 0, q2 = 0, q3 = 0, q4 = 0;

        for (Staff staff : staffList) {
            Quarter quarter = DateUtil.quarterEnum(staff.getCreateTime());
            switch (quarter) {
                case Q1:
                    q1++;
                    break;
                case Q2:
                    q2++;
                    break;
                case Q3:
                    q3++;
                    break;
                case Q4:
                    q4++;
            }

        }

        return Response.success(CollUtil.newArrayList(q1, q2, q3, q4));
    }

    // 统计员工的基本数据
    public ResponseDTO getCountData() {
        // 获取总员工数
        long totalNum = staffService.count();
        // 获取状态正常的员工数
        long normalNum = staffService.count(new QueryWrapper<Staff>().eq("status", "1"));
        // 统计当日考勤数据
        Date date = new Date(System.currentTimeMillis());
        // 日期格式化
        String day = DateUtil.format(date, "yyyy-MM-dd");

        // 计算出当前日期有多少人迟到
        long lateNum = attendanceService.count(new QueryWrapper<Attendance>().eq("attendance_date", day).eq("status", AttendanceStatusEnum.LATE.getCode()));

        // 计算出当前日期有多少人早退
        long leaveEarlyNum = attendanceService.count(new QueryWrapper<Attendance>().eq("attendance_date", day).eq("status", AttendanceStatusEnum.LEAVE_EARLY.getCode()));

        // 计算出当前日期有多少人旷工
        long absenteeismNum = attendanceService.count(new QueryWrapper<Attendance>().eq("attendance_date", day).eq("status", AttendanceStatusEnum.ABSENTEEISM.getCode()));


        // 封装成map
        Map<String, Object> map = new HashMap<>();
        map.put("totalNum", totalNum);
        map.put("normalNum", normalNum);
        map.put("lateNum", lateNum);
        map.put("leaveEarlyNum", leaveEarlyNum);
        map.put("absenteeismNum", absenteeismNum);

        return Response.success(map);

    }

    // 获取城市社保数据
    public ResponseDTO getCityData() {
        // 查询前五条
        QueryWrapper<City> qw = new QueryWrapper<>();
        qw.last("limit 5");

        List<City> cityList = cityService.list(qw);

        return Response.success(cityList);
    }

    // 获取考勤数据
    public ResponseDTO getAttendanceData(Integer id, String month) {
        // 判断时间是否为空
        if (month == null || month.equals("")) {
            month = DateUtil.format(new Date(), "yyyyMM");
        }

        // 获取该月的天数列表
        String[] days = DatetimeUtil.getMonthDayList(month);

        // 出勤状态表
        List<Integer> list = new ArrayList<>();

        for (String day : days) {
            // 通过员工id和日期查询出该员工的日期考勤记录
            Attendance attendance = attendanceMapper.findByStaffId(id, day);
            if (attendance == null) { // 如果为空，则判断该天是否是周末，如果是则该天为请假状态，否则为正常状态
                Date date = DateUtil.parse(day, "yyyyMMdd").toSqlDate(); // 获取日期对象进行转换格式
                if (DateUtil.isWeekend(date)) { // 判断是否为周末
                    list.add(AttendanceStatusEnum.LEAVE.getCode());
                } else {
                    list.add(AttendanceStatusEnum.NORMAL.getCode());
                }
            } else {
                list.add(attendance.getStatus().getCode()); // 否则为考勤状态
            }
        }
        return Response.success(list);
    }

    // 获取各部门的考勤数据
    public ResponseDTO getDepartmentData() {
        // 获取所有一级部门
        List<Dept> parentList = deptService.list(new QueryWrapper<Dept>().eq("parent_id", 0));
        List<Map<String, Object>> mapList = new ArrayList<>();

        for (Dept parentDept : parentList) {
            // 获取该一级部门的所有二级部门
            List<Dept> list = deptService.list(new QueryWrapper<Dept>().eq("parent_id", parentDept.getId()));
            // 将该一级部门下的所有二级部门的id列表封装到ids中去，然后通过该id列表查询出所有员工的考勤数据
            List<Integer> ids = list.stream().map(Dept::getId).collect(Collectors.toList());
            // 计算出该部门下有多少员工
            long num = staffService.count(new QueryWrapper<Staff>().in("dept_id", ids));
            Map<String,Object> map = new HashMap<>();
            map.put("value", num);
            map.put("name", parentDept.getName());
            mapList.add(map);
        }
        return Response.success(mapList);
    }
}
